package team.nmsg.ge.system.controller;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import team.nmsg.ge.system.bean.PageObject;
import team.nmsg.ge.system.bean.SysBusinessLog;
import team.nmsg.ge.system.bean.SysOper;
import team.nmsg.ge.system.bean.SysRole;
import team.nmsg.ge.system.bean.SysUser;
import team.nmsg.ge.system.init.CommonDefine;
import team.nmsg.ge.system.init.shiro.SysAuthorizingRealm;
import team.nmsg.ge.system.service.ISystemLogService;
import team.nmsg.ge.system.service.IUserRoleService;
import team.nmsg.ge.system.util.MD5Encrypt;
import team.nmsg.ge.system.util.SysLanguageHelper;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


@Controller
@RequestMapping("sys")
public class SystemController extends BaseController{
	
	private static Logger logger =  LoggerFactory.getLogger(  SystemController.class );
	
	@Autowired
	IUserRoleService userRoleService = null;
	
	@Autowired
	ISystemLogService systemLogService = null;
    
    @RequestMapping("/userManage")
	public String userHome() {

		return "system/UserFrame";
	}
    
    @RequestMapping("/QueryUser")
	public String QueryUser( HttpServletRequest req,  HttpServletResponse resp ){
		JSONObject obj = new JSONObject();
		
		String sEcho = req.getParameter("sEcho");
		String startIndex = req.getParameter("iDisplayStart");
		String pageSize = req.getParameter("iDisplayLength");
		String searchText = getParaByConvert("searchText", req);
		
		SysUser user = new SysUser();
		user.setUsername(searchText);
		
		PageObject<SysUser> page = userRoleService.QueryUser( Integer.parseInt(pageSize) , 
				Integer.parseInt(startIndex) , user );
		JSONArray arr = new JSONArray();
		for(SysUser u :page.getCurrentEntitys() ){
			arr.add( u.toJson() );
		}
		obj.put("aaData", arr);
		obj.put("sEcho", sEcho );
		obj.put("iTotalRecords", page.getSumCount() );
		obj.put("iTotalDisplayRecords", page.getSumCount() );
		
		writeJson(obj, resp);
		return null;
	}
    
    @RequestMapping("/logs")
    public ModelAndView systemLog() {
		Map<String,Object> data = new HashMap<String,Object>();  
		Map<Integer, String> logTypes = CommonDefine.logTypeToDesc;		
		data.put("logTypes", logTypes);
		ModelAndView mv = new ModelAndView("system/SystemLog" , data);
		return mv;
	}
    
    @RequestMapping("/queryLogs")
	public String queryLogs(HttpServletRequest req,  HttpServletResponse resp){
		JSONObject obj = new JSONObject();
		String sEcho = req.getParameter("sEcho");
		String startIndex = req.getParameter("iDisplayStart");
		String pageSize = req.getParameter("iDisplayLength");
		String username = getParaByConvert("username", req);
		String startTime = req.getParameter("StartTime");
		String endTime = req.getParameter("EndTime");
		long _startTime = 0;
		long _endTime = 0;
		if(startTime!=null&&!"".equals(startTime)&&endTime!=null&&!"".equals(endTime)){
			SimpleDateFormat  sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
			String st1 = startTime.substring(0, 10);
			String st2 = startTime.substring(13);
			startTime = st1+" "+st2;
			String st3 = endTime.substring(0, 10);
			String st4 = endTime.substring(13);
			endTime = st3+" "+st4;
			try {
				Date date = sdf.parse(startTime);
				Date date3 = sdf.parse(endTime);
				_startTime = date.getTime();
				_endTime = date3.getTime();
			} catch (ParseException e) {
				logger.error(" SystemControllerExceptionHandler ::: " , e );
			}
			
		}
		
		String logType = req.getParameter("LogType");
		
		SysBusinessLog logBean = new SysBusinessLog();
		logBean.setOperUserName(username);
		logBean.setOperKey(logType);
		PageObject<SysBusinessLog> page = systemLogService.queryLogs( Integer.parseInt(pageSize) , 
				Integer.parseInt(startIndex) , logBean, _startTime,_endTime);
		
		JSONArray arr = new JSONArray();
		for(SysBusinessLog log:page.getCurrentEntitys()){
			String operDesc = log.getOperDesc();
			String operArgs = log.getOperArgs();
			Object[] array = null;
			if( !StringUtils.isEmpty(operArgs) ){
				JSONArray fromObject = JSONObject.parseArray(operArgs);
				array = fromObject.toArray();
			}
			String msg = SysLanguageHelper.getMsg(operDesc, array);
			log.setOperDesc(msg);
			String operKey = log.getOperKey();
			String string = CommonDefine.logTypeToDesc.get(Integer.parseInt(operKey));
			JSONObject json = log.toJson();
			json.put("logType", string);
			arr.add( json );
		}
		
		obj.put("aaData", arr);
		obj.put("sEcho", sEcho );
		obj.put("iTotalRecords", page.getSumCount() );
		obj.put("iTotalDisplayRecords", page.getSumCount() );
		
		writeJson(obj, resp);
		return null;
		
	}
    
	@RequestMapping("/deleteLogByID")
	public String deleteLogByID(HttpServletRequest req,  HttpServletResponse resp){
		JSONObject obj = new JSONObject();
		String[] logIds = req.getParameterValues("logId[]");
		try {
			boolean result=systemLogService.deleteLogById(logIds);
			obj.put("result", result);
		} catch (Exception e) {
			logger.error(" SystemControllerExceptionHandler ::: " , e );
		}
		writeJson(obj, resp);
		return null;
	}
	
	    
	    @RequestMapping("/findAllRoles")
		public String findAllRoles(HttpServletRequest req, HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try {

				List<SysRole> findAllRoles = userRoleService.findAllRoles();

				JSONArray arr = new JSONArray();
				for (SysRole r : findAllRoles) {
					arr.add(r.toJson());
				}

				obj.put("result", arr);
				obj.put("aaData", arr);
			} catch (Exception e) {
				obj.put("result", null);
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
	    
	    @RequiresPermissions("AddUser")
	    @RequestMapping("/addSysUser")
		public String addSysUser(HttpServletRequest req, HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try {
				String uname = req.getParameter("uname");
				String upass = req.getParameter("upass");
				String phone = req.getParameter("phone");
				String email = req.getParameter("email");
				String[] roleids = req.getParameterValues("roles[]");//角色操作
				Set<SysRole> roles = new HashSet<SysRole>();
				SysUser sysUser = new SysUser();
				if(roleids!=null){
					for(String id:roleids){
						SysRole nmsRole = new SysRole();
						nmsRole.setRoleId(Integer.parseInt(id));
						roles.add(nmsRole);
					}
					sysUser.setRoles(roles);
				}else{
					sysUser.setRoles(null);
				}
				sysUser.setUsername(uname);
				sysUser.setPassword(MD5Encrypt.getMD5Str(upass));
				sysUser.setUserRemark("");
				long nowTime = System.currentTimeMillis();
				sysUser.setCreateTimestamp(nowTime);
				sysUser.setLastUpdateTimestamp(nowTime);
				sysUser.setUserStatus(SysUser.USER_STATUS_NORMAL);
				sysUser.setLoginCounter(0l);
				sysUser.setPhoneNo(phone);
				sysUser.setEmail(email);
				sysUser = userRoleService.addSysUser(sysUser);
				if (sysUser != null && sysUser.getUserId() != null) {
					obj.put("result", true);
				}
			} catch (Exception e) {
				obj.put("result", false);
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
	    
	    @RequiresPermissions("DelUser")
	    @RequestMapping("/DeleteUserByID")
		public void DeleteUserByID( HttpServletRequest req,  HttpServletResponse resp){
			JSONObject obj = new JSONObject();
			String[] UserIds =  req.getParameterValues("userID[]");
			boolean flag = false;
			for(String id:UserIds){
				if(id.equals("1")){
					flag = true;
				}
			}
			if(flag){
				obj.put("results",false);			
			}else{
				userRoleService.deleteUserByID(UserIds);
				obj.put("results", true);
			}
			writeJson(obj, resp);
			
		}
	    
	    @RequestMapping("/findAllRoles_userRole")
		public String queryUserRole(HttpServletRequest req,  HttpServletResponse resp){
			JSONObject obj = new JSONObject();
			try {

				List<SysRole> findAllRoles = userRoleService.findAllRoles();
				JSONArray arr = new JSONArray();
				for (SysRole r : findAllRoles) {
					arr.add(r.toJson());
				}
				obj.put("result", arr);        //所有角色
				
				String userid = req.getParameter("uid");
				SysUser sysUser = new SysUser();
				sysUser = userRoleService.queryUserById(Integer.parseInt(userid));
				JSONArray arr2 = new JSONArray();
				for(SysRole role:sysUser.getRoles()){
					arr2.add( role.toJson() );
				}
				obj.put("userInfo", sysUser.toJson());
				obj.put("result2",arr2);       //该用户所拥有的角色
			} catch (Exception e) {
				obj.put("result", null);
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
			
		}
	    
	    @RequiresPermissions("UpdUser")
		@RequestMapping("/updataUser")
		public void updataUser( HttpServletRequest req,  HttpServletResponse resp){
			String upass = req.getParameter("upass");
			String uStatus = req.getParameter("uStatus");
			String uRemark = req.getParameter("uRemark");
			String uPhone = req.getParameter("uPhone");
			String uEmail = req.getParameter("uEmail");
			String uid = req.getParameter("uid");
			String[] roleids = req.getParameterValues("roles[]");//角色操作
			Set<SysRole> roles = new HashSet<SysRole>();
			String username = req.getParameter("username");
			SysUser sysUser = new SysUser();
			if(roleids!=null){
				for(String id:roleids){
					SysRole sysRole = new SysRole();
					sysRole.setRoleId(Integer.parseInt(id));
					roles.add(sysRole);
				}
				sysUser.setRoles(roles);
			}else{
				sysUser.setRoles(null);
			}
			
			if(!upass.equals("")){
				sysUser.setPassword(MD5Encrypt.getMD5Str(upass));
			}
			sysUser.setUserStatus(Integer.parseInt(uStatus));
			sysUser.setUserRemark(uRemark);
			sysUser.setPhoneNo(uPhone);
			sysUser.setEmail(uEmail);
			sysUser.setUserId(Integer.parseInt(uid));
			sysUser.setUsername(username);
			
			userRoleService.updUser(sysUser);
			
			JSONObject obj = new JSONObject();
			obj.put("results", 1);
			
			writeJson(obj, resp);
		}
		
		@RequestMapping("/roleManage")
		public String roleManage() {

			return "system/RoleFrame";
		}
		
		@RequestMapping("/findAllOpers")
		public String findAllOpers(HttpServletRequest req, HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			String operId,operName,nmsPoId;
			try {
				JSONArray arr = new JSONArray();
				List<SysOper> findAllOpers = userRoleService.findAllOpers();
				for (SysOper p : findAllOpers) {
					JSONObject ob = new JSONObject();
					 operId=p.toJson().getString("operId");
					 operName=p.toJson().getString("operName");
					 nmsPoId=p.toJson().getString("sysPoId");
					 ob.put("id",operId);
					 ob.put("text",operName);
					 if(Integer.valueOf(nmsPoId)==-1){
						 ob.put("parent", "#");
					 }
					 else{
						 ob.put("parent", nmsPoId);
					 }
					 arr.add(ob);
				}
				obj.put("result",arr);
			} catch (Exception e) {
				obj.put("result", null);
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
	    
		@RequestMapping("/findAuthByRole")
		public String findAuthByRole(HttpServletRequest req,
				HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try {
				JSONArray arr = new JSONArray();
				String rid = req.getParameter("rid");
				Set<SysOper> findAuthByRole = userRoleService.getAuthByRole(rid);
				for (SysOper r : findAuthByRole) {
					arr.add(r.getOperId());
				}

				obj.put("result", arr);
			} catch (Exception e) {
				obj.put("result", null);
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;

		}
		@RequiresPermissions("AddRole")
		@RequestMapping("/addsysRole")
		public String addsysRole(HttpServletRequest req, HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try {
				JSONArray arr = new JSONArray();
				String rolename = req.getParameter("rolename");
				String roleremark = req.getParameter("roleremark");
				SysRole sysRole = new SysRole();
				sysRole.setRoleName(rolename);
				sysRole.setRoleRemark(roleremark);
				sysRole.setCreateTimestamp(System.currentTimeMillis());

				sysRole = userRoleService.addSysRole(sysRole);

				if (sysRole != null) {
					arr.add(sysRole.toJson());
					obj.put("result", arr);
				}
			} catch (Exception e) {
				obj.put("result", false);
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
		@RequiresPermissions("DelRole")
		@RequestMapping("/deletesysRole")
		public String deleteSysRole(HttpServletRequest req,  HttpServletResponse resp){
			JSONObject obj = new JSONObject();
			try {
//				String rootId = NMSUserRoleParser.admins.getRoleId().toString();
				String rid=req.getParameter("rid");
//				String rname=req.getParameter("rname");
				if(!"1".equals(rid)){
					boolean deletenmsrole=userRoleService.delSysRole(rid);
					obj.put("result", deletenmsrole);
				}
				else{
					obj.put("result", "isAdmin");
				}
			}catch (Exception e) {	
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
		@RequiresPermissions("GrantOperToRole")
		@RequestMapping("/updGrantOperToRole")
		public String updGrantOperToRole(HttpServletRequest req,
				HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try{
			String rname=req.getParameter("rname");
			int rid = Integer.valueOf(req.getParameter("roleId"));
			String[] operspath = req.getParameterValues("opers[]");//权限节点路径
			String[] operId;//权限id
			String[] operIds=null;//权限id集合
			 List<String> list = new ArrayList<String>();
			if(operspath!=null){//获取路径上的权限
				for(int i=0;i<operspath.length;i++){
					operId=operspath[i].split("/");
					for(int j=0;j<operId.length;j++){ 
							if(!list.contains(operId[j])) {  //去除重复父节点
								list.add(operId[j]);  	             
							}
					}
				}
				 operIds =  list.toArray(new String[1]);
			}
			
			userRoleService.updModifyOperToRole(rid, operIds,rname);
			obj.put("result", true);
			}catch (Exception e) {
				obj.put("result", null);
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;

		}
		
		@RequestMapping("/changePassword")
		public String changePassword(HttpServletRequest req, HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try {
			SysUser user = (SysUser)SysAuthorizingRealm.getShiroSessionAttr("user");
			String oldPassword = req.getParameter("oldPassword");
			String newPassword = req.getParameter("newPassword");
			boolean changePassword=userRoleService.updChangePassword(user, oldPassword, newPassword);
			obj.put("result", changePassword);
			}catch (Exception e) {	
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
		
		@RequestMapping("/getPublishThread")
		public String getPublishThread(HttpServletRequest req, HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try {
				
				JSONArray allClientInfo = userRoleService.getAllClientInfo();
				obj.put("onlineUsers", allClientInfo);
			}catch (Exception e) {	
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
		
		@RequestMapping("/monitor")
		public String monitor() {

			return "system/MonitorFrame";
		}
		
		@RequestMapping("/setPublish_key")
		public String setPublish_key(HttpServletRequest req, HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try {
				String status = req.getParameter("status");
				int setPublish_value = systemLogService.setPublish_value(status);
				obj.put("result", setPublish_value == 1 ? true : false);
				
			}catch (Exception e) {	
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
		
		@RequestMapping("/setDownload_key")
		public String setDownload_key(HttpServletRequest req, HttpServletResponse resp) {
			JSONObject obj = new JSONObject();
			try {
				String status = req.getParameter("status");
				int setDownload_value = systemLogService.setDownload_key(status);
				obj.put("result", setDownload_value == 1 ? true : false);
				
			}catch (Exception e) {	
				logger.error("", e);
			}
			writeJson(obj, resp);
			return null;
		}
		
	    
}
